package net.chrone.quickpayapi.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import net.chrone.quickpayapi.model.PmsBankInf;
import net.chrone.quickpayapi.model.RegionInfo;
import net.chrone.quickpayapi.model.RootBank;
import net.chrone.quickpayapi.service.PmsBankInfService;
import net.chrone.quickpayapi.service.RedisService;
import net.chrone.quickpayapi.service.RegionInfoService;
import net.chrone.quickpayapi.service.RootBankService;
import net.chrone.quickpayapi.service.SeqService;
import net.chrone.quickpayapi.util.RedisClient;

@Service("redisService")
public class RedisServiceImpl implements RedisService {
	
	@Autowired
	private SeqService seqService;
	@Autowired
	private RootBankService rootBankService;
	@Autowired
	private PmsBankInfService pmsBankService;
	@Autowired
	private RegionInfoService regionInfoService;

	@Override
	public RegionInfo findCity(String cityCd) {
		String json = RedisClient.getByKey(RedisClient.CACHE_PREFIX_CITY+cityCd);
		RegionInfo regionInfo = null;
		if(StringUtils.isEmpty(json)){
			regionInfo = regionInfoService.findById(cityCd);
			RedisClient.set(RedisClient.CACHE_PREFIX_CITY+cityCd, JSON.toJSONString(regionInfo));
		}else{
			regionInfo = JSON.parseObject(json, RegionInfo.class);
		}
		return regionInfo;
	}

	@Override
	public RootBank findRootBank(String bankNo) {
		String json = RedisClient.getByKey(RedisClient.CACHE_PREFIX_ROOT_BANK+bankNo);
		RootBank rootBank = null;
		if(StringUtils.isEmpty(json)||"null".equals(json)){
			rootBank = rootBankService.findById(bankNo);
			RedisClient.set(RedisClient.CACHE_PREFIX_ROOT_BANK+bankNo, JSON.toJSONString(rootBank));
		}else{
			rootBank = JSON.parseObject(json, RootBank.class);
		}
		return rootBank;
	}

	@Override
	public PmsBankInf findPmsBank(String pmsBankCd) {
		String json = RedisClient.getByKey(RedisClient.CACHE_PREFIX_PMS_BANK+pmsBankCd);
		PmsBankInf pmsBankInfo = null;
		if(StringUtils.isEmpty(json)){
			pmsBankInfo = pmsBankService.find(pmsBankCd);
			RedisClient.set(RedisClient.CACHE_PREFIX_PMS_BANK+pmsBankCd, JSON.toJSONString(pmsBankInfo));
		}else{
			pmsBankInfo = JSON.parseObject(json, PmsBankInf.class);
		}
		return pmsBankInfo;
	}

	
	@Override
	public String getIdFromRedis(String id) {
		String key = RedisClient.CACHE_PREFIX_ID+id;
		if(!RedisClient.exisit(key)){
			RedisClient.set(key, "0");
			 return seqService.format(0, 7);
		}else{
			Long num = RedisClient.inc(key);
			if(num==9999999){
				RedisClient.set(key, "0");//重置
			}
			return seqService.format(num, 7);
		}
	}
}
